class WebSocketWrapper {
    constructor(url) {
        this.url = url;
        this.websocket = null;
        this.heartBeatInterval = null;
        this.reconnectInterval = null;
        this.reconnectCount = 0;
        this.maxReconnectCount = 5;
        this.onOpen = null;
        this.onClose = null;
        this.onMessage = null;
        this.onError = null;
    }
    // 连接
    connect() {
        this.websocket = new WebSocket(this.url);
        this.websocket.onopen = (event) => {
            this.reconnectCount = 0;
            this.startHeartBeat();
            if (this.onOpen) {
                this.onOpen(event);
            }
        };
        this.websocket.onclose = (event) => {
            this.stopHeartBeat();
            if (this.onClose) {
                this.onClose(event);
            }
            if (this.reconnectCount < this.maxReconnectCount) {
                this.reconnectCount++;
                this.reconnectInterval = setTimeout(() => {
                    this.connect();
                }, 1000 * this.reconnectCount);
            }
        };
        this.websocket.onmessage = (event) => {
            if (this.onMessage) {
                Bus.$emit('onmessage', event)
                this.onMessage(event);
            }
        };
        this.websocket.onerror = (event) => {
            if (this.onError) {
                this.onError(event);
                setTimeout(() => {
                    this.connect()
                }, 10000)
            }
        };
    }
    // 发送消息
    send(data) {
        if (this.websocket) {
            this.websocket.send(data);
        }
    }
    // 关闭连接
    close() {
        this.stopHeartBeat();
        if (this.websocket) {
            this.websocket.close();
        }
    }

    startHeartBeat() {
        this.heartBeatInterval = setInterval(() => {
            this.send('ping');
        }, 30000);
    }

    stopHeartBeat() {
        clearInterval(this.heartBeatInterval);
    }
}
